import { memo, useMemo, useEffect } from 'react';
import { Flex, Text, Spinner } from '@chakra-ui/react';
import { useAppDispatch } from 'store/storeHooks';
import { modelSelected } from 'features/parameters/store/actions';
import { MODEL_TYPE_MAP } from 'features/parameters/types/constants';
import { modelIdToMainModelParam } from 'features/parameters/util/modelIdToMainModelParam';
import { forEach } from 'lodash-es';
import { NON_REFINER_BASE_MODELS } from 'services/api/constants';
import { useGetMainModelsQuery } from 'services/api/endpoints/models';

const ParamMainModel = () => {
  const dispatch = useAppDispatch();

  const { data: mainModels, isLoading } = useGetMainModelsQuery(
    NON_REFINER_BASE_MODELS
  );

  const data = useMemo(() => {
    if (!mainModels) {
      return [];
    }

    const data: any[] = [];

    forEach(mainModels.entities, (model, id) => {
      if (!model) {
        return;
      }

      data.push({
        value: id,
        label: model.model_name,
        group: MODEL_TYPE_MAP[model.base_model],
      });
    });

    return data;
  }, [mainModels]);

  useEffect(() => {
    if (!isLoading && data.length) {
      const { value } = data.find((i) => i.label === '图蝇V8');
      const newModel = modelIdToMainModelParam(value);
      if (!newModel) {
        return;
      }
      dispatch(modelSelected(newModel));
    }
  }, [isLoading, data, dispatch]);

  return isLoading ? (
    <Flex position="absolute" bottom="0" right="0" gap="2" p="2">
      <Spinner size="sm" />
      <Text fontSize="xs">Loading Models</Text>
    </Flex>
  ) : null;
};

export default memo(ParamMainModel);
